<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
      <el-form-item label="设备编号" prop="dev_code">
        <el-input v-model.trim="queryParams.dev_code" placeholder="请输入设备编号" clearable style="width: 240px"
          @keyup.enter="handleQuery" @clear="handleQuery" @input="handleInput" />
      </el-form-item>
      <el-form-item label="告警时间范围" prop="state" label-width="100px">
        <el-date-picker
          v-model="queryParams.value"
          type="datetimerange"
          value-format="YYYY-MM-DD HH:mm:ss"
          :shortcuts="shortcuts"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleDateChange"
          align="right">
      </el-date-picker>
      </el-form-item>
      <el-form-item label="处理状态" prop="state" label-width="100px">
        <el-select v-model="queryParams.state" clearable placeholder="请选择处理状态" @change="handleQuery"
          style="width: 240px">
          <el-option v-for="item in options1" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>
    <!-- 表格数据 -->
    <el-table v-loading="loading" size="large" :max-height="tableHeight" :data="dataList">
      <el-table-column type="index" label="序号" width="120" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="监测站" v-if="columns[0].visible" prop="sta_Name" align="center" width="200" />
      <el-table-column label="所属设备" v-if="columns[1].visible" prop="dev_Name" align="center" width="200" />
      <el-table-column label="设备编号" v-if="columns[2].visible" prop="dev_id" align="center" width="200" />
      <el-table-column label="故障" v-if="columns[3].visible" align="center" width="100">
        <template #default="scope">
          <span>{{ getVoltageStatus(scope.row.type)  }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上报时间" v-if="columns[4].visible" prop="alarmtime" align="center" width="200" />
      <el-table-column label="处理状态" v-if="columns[5].visible" align="center" width="100">
        <template #default="scope">
          <span>{{ scope.row.state==1?'已处理':'未处理' }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" min-width="240px" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleUpdate(scope.row)">详情</el-button>
          <el-button link type="primary" v-if="scope.row.state === 0" icon="Edit" @click="handleDelete(scope.row)">处理</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete2(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title2" v-model="open2" width="700px" append-to-body :close-on-click-modal="false">
      <el-form ref="roleRef2" :model="form2"  label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="A相电压">
              <el-input v-model.trim="form2.ua" boe readonly maxlength="30" placeholder="-" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="A相电压状态" >
              <el-input :value="getVoltageStatus(form2.ua_st)" readonly maxlength="30" placeholder="-" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="B相电压">
              <el-input v-model.trim="form2.ub" readonly maxlength="30" placeholder="-" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="B相电压状态">
              <el-input :value="getVoltageStatus(form2.ub_st)" readonly maxlength="30" placeholder="-" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="C相电压">
              <el-input v-model.trim="form2.uc" readonly maxlength="30" placeholder="-" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="C相电压状态">
              <el-input :value="getVoltageStatus(form2.uc_st)" readonly maxlength="30" placeholder="-" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="3U0电压">
              <el-input v-model.trim="form2.u0" readonly maxlength="30" placeholder="-" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="3U0电压状态">
              <el-input :value="getVoltageStatus(form2.u0_st)" readonly maxlength="30" placeholder="-" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="告警时间" v-if="form2.ts">
              <el-input v-model.trim="form2.ts" readonly maxlength="30" placeholder="-" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=""  label-width="30">
              <span @click="toD(form2)" style="color: #409eff;font-size: 14px;display: flex;align-items: center;">查看波形数据 <el-icon><DArrowRight /></el-icon></span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { useInfoStore } from '@/store/modules/info.js'
import { id } from 'element-plus/es/locales.mjs';
const userInfo = useInfoStore();

const router = useRouter();
const route = useRoute();

const { proxy } = getCurrentInstance();
// const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
const tableHeight = ref(document.documentElement.scrollHeight - 280 + "px");


const dataList = ref([]);
const open = ref(false);
const open2 = ref(false);
const loading = ref(false);
const disabled = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const title2 = ref("");
const dateRange = ref([]);
const menuOptions = ref([]);
const deptOptions = ref([]);
const menuRef = ref(null);
const options1 = ref([
  { id: 0, name: "未处理" },
  { id: 1, name: "已处理" },
]);
const options2 = ref([]); //监测站点
const options3 = ref([]); //线路列表
const cascaderRef = ref(null);

const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 7)
      return [start, end]
    },
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 1)
      return [start, end]
    },
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 3)
      return [start, end]
    },
  },
]
  
// 列显隐信息
const columns = ref([
  { key: 1, label: `所属监测站`, visible: true },
  { key: 2, label: `所属设备`, visible: true },
  { key: 3, label: `设备编号`, visible: true },
  { key: 4, label: `故障`, visible: true },
  { key: 5, label: `上报时间`, visible: true },
  { key: 6, label: `处理状态`, visible: true },
]);
// 电压状态映射函数
const getVoltageStatus = computed(() => (status) => {
  const statusMap = {
    1: '欠压',
    2: '超压',
    3: '短路',
    4: 'PT断线',
  };
  return statusMap[status] || status;
});

const data = reactive({
  form2: {
    id: null,
    ua: null, 
    ua_st: null,
    ub: null,
    ub_st: null,
    over: null,
    uc: null,
    uc_st: null,
    u0: null,
    u0_st: null,
    ts: null,
  },
  queryParams: {
    pageNo: 1,
    pageSize: 10,
    dt1: null,//开始时间
    dt2: null,//结束时间
    dev_code: '',//设备编号
    state: null,//是否处理：0未处理、1已处理
    value: null,//时间暂存值
  },
  rules: {
    ent_id: [{ required: true, message: "所属企业不能为空", trigger: "blur" }],
    dev_name: [{ required: true, message: "设备名称不能为空", trigger: "blur" }],
    dev_code: [{ required: true, message: "设备编码不能为空", trigger: "blur" }],
    station_id: [{ required: true, message: "请选择监测站", trigger: "blur" }],
    line_code: [{ required: true, message: "请选择线路", trigger: "blur" }],
  },

});

const { queryParams, form, form2, rules ,rules2} = toRefs(data);

// 时间范围选中处理 
const handleDateChange = (val) => {
  if (val?.length > 0) {
    console.log(11);
    queryParams.value.dt1 = val[0];
    queryParams.value.dt2 = val[1];
  } else {
    queryParams.value.dt1 = null;
    queryParams.value.dt2 = null;
  }
  getList();
}

// 自定义校验函数
const validateTypeOrSpec = (rule, value, callback) => {
  if (!form.value.types && !form.value.specifications) {
    callback(new Error('型号和规格至少输入一项'));
  } else {
    callback();
  }
};

// 详情
function toD(row) {
  router.push({
    path: '/public/cloudTv/chartDetails2',
    query: {
      id:row.id,
    }
  });
}

// 更新校验规则
rules.value.types = { validator: validateTypeOrSpec, trigger: 'blur' };
rules.value.specifications = { validator: validateTypeOrSpec, trigger: 'blur' };

//获取监测站
function handleEntChange(value) {
  // console.log(options1.value);
  proxy.cloudTv_API.GetStationList({
    enterpriseID: value,
  }).then(response => {
    if (response.data?.length > 0) {
      options2.value = response.data || [];
      options2.value.forEach(item => {
        item.station_Name = item.staName;
      });
      if(!form.value.station_id){ //如果监测站无值，则默认第一条
         form.value.station_id = options2.value[0].id;
      }
      getLineList(form.value.station_id);
    }else{
      form.value.station_id = null;
      options2.value =  [];
      form.value.line_code = null;
      options3.value =  [];
      proxy.$modal.msgError("当前企业还没有添加监测站~");
    }
  });
}

//获取监测--母线-支线
function getLineList(value) {
  proxy.cloudTv_API.GetMasterLineList({
    stationID: value,
    state: 1,
  }).then(response => {
    if (response.data?.length > 0) {
      options3.value = response.data || [];
      if(!form.value.line_code){ //如果线路无值，则默认第一条
        form.value.line_code = options3.value[0].line_code;
        form.value.line_id = options3.value[0].id;
      }
    }else{
      form.value.line_code = null;
      form.value.line_id = null;
      options3.value =  [];
      proxy.$modal.msgError("当前监测站还没有线路~");
    }
  });
}

function handleEntChange2(value) {
  form.value.line_code = null;//选中监测站 清空支线
  form.value.line_id = null;
  getLineList(value);
}
  // 主动关闭弹层
function handleCascaderChange(e) {
    // 获取当前选中的节点列表
    const item = cascaderRef.value.getCheckedNodes()[0].data;
    form.value.line_type = item?.master_LineID?1:0;
    form.value.line_id = item.id;
    cascaderRef.value.togglePopperVisible(false)
}
/** 查询列表 */
function getList() {
  loading.value = true;
  proxy.cloudTv_API.ShowAlarmModPage(queryParams.value).then(response => {
    dataList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
  });
}
// 输入时触发的防抖处理函数
let timer = null;
function handleInput() {
  clearTimeout(timer);
  timer = setTimeout(handleQuery, 300);
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNo = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  queryParams.value = {
    pageNo: 1,
    pageSize: 10,
    dt1: null,//开始时间
    dt2: null,//结束时间
    dev_code: '',//设备编号
    state: null,//是否处理：0未处理、1已处理
    value: null,//时间暂存值
  }
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 处理按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认已处理设备"' + row.dev_Name + '"的数据项?').then(function () {
    proxy.cloudTv_API.UpdateVotaState({
        id: row.id,
      }).then(response => {
        getList();
        proxy.$modal.msgSuccess("处理成功");
      });
  })
}
/** 删除按钮操作 */
function handleDelete2(row) {
  proxy.$modal.confirm('是否确认删除电压告警时间"' + row.alarmtime + '"的数据项?').then(function () {
    proxy.cloudTv_API.DelVotaState({
        id: row.id,
      }).then(response => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      });
  })
}


/** 重置新增的表单以及其他数据  */
function reset() {
  form2.value = {
    id: null,
    ua: null,
    ua_st: null,
    ub: null,
    ub_st: null,
    over: null,
    uc: null,
    uc_st: null,
    u0: null,
    u0_st: null,
    ts: null,
  };
}
/** 新增物料 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增设备";
}

/** 修改 */
function handleUpdate(row) {
  const statusMap = {
    1: '欠压',
    2: '超压',
    3: '短路',
    4: 'PT断线',
  };
  router.push({
    path: '/public/cloudTv/chartDetails2',
    query: {
      id:row.id,
      alarmtime:row.alarmtime,
      type:statusMap[row.type],
    }
  });
  // proxy.cloudTv_API.FindOneAlarm({
  //   id: row.id,
  // }).then(res => {
  //   const mes = JSON.parse(res.data.mes);
  //   reset();
  //   Object.keys(form2.value).forEach(key => {
  //     form2.value[key] = mes[key];
  //   });
  //   form2.value.id = row.id;
  //   form2.value.ts = row.alarmtime;
  //   open2.value = true;
  //   title2.value = "详细信息";
  // });
}

// 路由跳转 - 详情
function handleRouter(row) {
  router.push(`/public/cloudTv/chartDetails?id=${row.id}`)
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      if (form.value.id) {
        proxy.cloudTv_API.EditDevice({
          ...form.value,
        }).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        proxy.cloudTv_API.AddDevice({
          ...form.value,
        }).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 提交按钮 */
function submitForm2() {
  proxy.$refs["roleRef2"].validate(valid => {
    if (valid) {
      proxy.cloudTv_API.UpDateDevCFG({
        ...form2.value,
      }).then(response => {
        proxy.$modal.msgSuccess("修改成功");
        open2.value = false;
      });
    }
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

onMounted(() => {
  if(route.query.dev_code){
    queryParams.value.dev_code = route.query.dev_code;
  }
  getList();
})


</script>

<style lang="scss" scoped>
.el-input-number {
  width: 190px;
}

.required-star {
  color: #F56C6C;
  margin-right: 4px;
}
</style>